import { ref, onMounted, onUnmounted } from 'vue'

export function useContextMenu(container) {
  const x = ref(0)
  const y = ref(0)
  const visible = ref(false)
  const CUSTOM_CONTEXTMENU_EVENT = 'custom-contextmenu'

  const contextmenuHandler = (e) => {
    e.preventDefault()
    e.stopPropagation()
    x.value = e.clientX
    y.value = e.clientY
    window.dispatchEvent(
      new Event(CUSTOM_CONTEXTMENU_EVENT, {
        bubbles: true, // 让事件冒泡
        cancelable: true, // 允许事件被取消
        detail: {} // 附加事件数据
      })
    )
    visible.value = true
  }
  const closeHandler = () => {
    visible.value = false
  }
  onMounted(() => {
    window.addEventListener(CUSTOM_CONTEXTMENU_EVENT, (e) => {
      // console.log('closeHandler');
      closeHandler()
    })
    container.value.addEventListener('contextmenu', contextmenuHandler)
    window.addEventListener('click', closeHandler)
    window.addEventListener('contextmenu', closeHandler)
  })

  onUnmounted(() => {
    container.value.removeEventListener('contextmenu', contextmenuHandler)
    window.removeEventListener('click', closeHandler)
    window.removeEventListener('contextmenu', closeHandler)
  })

  return {
    x,
    y,
    visible
  }
}
